/**
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑
 */
import { getLoginUserInfo, login } from '@/api/user'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken
} from '@/utils/accessToken'
// import { title, tokenName } from '@/config'
import settings from '@config/index'
import { message, notification } from 'ant-design-vue'

const state = () => ({
  accessToken: getAccessToken(),
  username: '',
  avatar: '',
  admin: false,
  role: [],
  authorities: []
})
const getters = {
  accessToken: state => state.accessToken,
  username: state => state.username,
  avatar: state => state.avatar,
  admin: state => state.admin,
  role: state => state.role,
  authorities: state => state.authorities
}
const mutations = {
  /**
   * @description 设置accessToken
   * @param {*} state
   * @param {*} accessToken
   */
  SET_ACCESS_TOKEN(state, accessToken) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  /**
   * @description 设置用户名
   * @param {*} state
   * @param {*} username
   */
  SET_USER_NAME(state, username) {
    state.username = username
  },
  /**
   * @description 设置头像
   * @param {*} state
   * @param {*} avatar
   */
  SET_USER_AVATAR(state, avatar) {
    state.avatar = avatar
  },
  SET_USER_FULL(state, admin) {
    state.admin = admin
  },
  SET_USER_ROLES(state, role) {
    state.role = role
  },
  SET_USER_AUTHORITIES(state, authorities) {
    state.authorities = authorities
  }
}
const actions = {
  /**
   * @description 登录
   * @param {*} { commit }
   * @param {*} userInfo
   */
  async login({ commit }, userInfo) {
    const response = await login(userInfo)
    const accessToken = response.dataSet.access_token
    if (accessToken) {
      commit('SET_ACCESS_TOKEN', accessToken)
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
            ? '上午好'
            : hour <= 13
              ? '中午好'
              : hour < 18
                ? '下午好'
                : '晚上好'
      notification.open({
        message: `欢迎登录${settings.title}`,
        description: `${thisTime}！`
      })
    } else {
      message.error(`登录接口异常，未正确返回${settings.tokenName}...`)
    }
  },
  /**
   * @description 设置虚拟角色
   * @param {*} { commit, dispatch }
   */
  async setVirtualRoles({ commit, dispatch }) {
    dispatch('user/setFull', true, { root: true })
    commit('SET_USER_AVATAR', 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif')
    commit('SET_USER_NAME', 'admin(未开启登录拦截)')
  },
  /**
   * 获取登录用户的相关信息
   */
  async getLoginUserInfo({ commit, dispatch }) {
    let response = await getLoginUserInfo()
    const  data = response.dataSet[0]
    if (!data) {
      message.error('验证失败，请重新登录...')
      return false
    }
    let { username, avatar, roles, authorities } = data
    if (username && roles && Array.isArray(roles)) {
      dispatch('user/setRole', roles, { root: true })
      if (authorities && authorities.length > 0)
        dispatch('user/setAuthorities', authorities, { root: true })
      commit('SET_USER_NAME', username)
      commit('SET_USER_AVATAR', avatar)
    } else {
      message.error('用户信息接口异常')
    }
  },

  /**
   * @description 退出登录
   * @param {*} { dispatch }
   */
  async logout({ dispatch }) {
    // await logout(state.accessToken)
    await dispatch('resetAll')
  },
  /**
   * @description 重置accessToken、roles、authorities、router等
   * @param {*} { commit, dispatch }
   */
  async resetAll({ dispatch }) {
    await dispatch('setAccessToken', '')
    await dispatch('user/setFull', false, { root: true })
    await dispatch('user/setRole', [], { root: true })
    await dispatch('user/setAuthorities', [], { root: true })
    removeAccessToken()
  },
  /**
   * @description 设置token
   */
  setAccessToken({ commit }, accessToken) {
    commit('SET_ACCESS_TOKEN', accessToken)
  },
  setFull({ commit }, admin) {
    commit('SET_USER_FULL', admin)
  },
  setRole({ commit }, role) {
    commit('SET_USER_ROLES', role)
  },
  setAuthorities({ commit }, authorities) {
    commit('SET_USER_AUTHORITIES', authorities)
  }
}
export default { namespaced: true, state, getters, mutations, actions }
